#include <glib-object.h>
#include <json-glib/json-glib.h>
#include <json-glib/json-gobject.h>

#include <gio/gio.h>
#include <string.h>
#include "mqtt.h"

#define TS_TYPE_DATA ts_data_get_type()
#define TS_DATA(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), TS_TYPE_DATA, TSData))
typedef struct _TSData		TSData;
typedef struct _TSDataClass	TSDataClass;
struct _TSData
{
	GObject parent_instance;

	gchar *ip;

	TSData *next;
};
struct _TSDataClass
{
	GObjectClass parent_class;
};
GType ts_data_get_type(void);
G_DEFINE_TYPE (TSData, ts_data, G_TYPE_OBJECT);
enum {
	PROP1_0,

	PROP_IP,
	PROP_NEXT,
};
static void
ts_data_init (TSData *object)
{
	object->ip = NULL;//g_strdup ("test");
}
static void
ts_data_set_property (GObject *gobject,
		guint prop_id,
		const GValue *value,
		GParamSpec *pspec)
{
	switch (prop_id) {
		case PROP_IP:
			g_free (TS_DATA(gobject)->ip);
			TS_DATA(gobject)->ip = g_value_dup_string (value);
			break;
		default:
			break;
	}
}
static void
ts_data_get_property (GObject *gobject,
		guint prop_id,
		GValue *value,
		GParamSpec *pspec)
{
	switch (prop_id) {
		case PROP_IP:
			g_value_set_string(value, TS_DATA(gobject)->ip);
			break;
		default:
			break;
	}
}
static void
ts_data_class_init (TSDataClass *klass)
{
	GObjectClass *gobject_class = G_OBJECT_CLASS(klass);

	gobject_class->set_property = ts_data_set_property;
	gobject_class->get_property = ts_data_get_property;
	//gobject_class->finalize = ts_object_finalize;

	g_object_class_install_property(gobject_class, PROP_IP,
			g_param_spec_string ("ip", "Ip", "Ip",
				NULL, G_PARAM_READWRITE));
}
#define TS_TYPE_OBJECT ts_object_get_type()
#define TS_OBJECT(obj) (G_TYPE_CHECK_INSTANCE_CAST ((obj), TS_TYPE_OBJECT, TSObject))
typedef struct _TSObject	TSObject;
typedef struct _TSObjectClass	TSObjectClass;
struct _TSObject
{
	GObject parent_instance;

	gchar *version;
	TSData *data;
};
struct _TSObjectClass
{
	GObjectClass parent_class;
};
GType ts_object_get_type(void);
G_DEFINE_TYPE (TSObject, ts_object, G_TYPE_OBJECT);
enum {
	PROP_0,

	PROP_VERSION,
	PROP_DATA,
};
static void
ts_object_init (TSObject *object)
{
	object->version = NULL;//g_strdup ("test");
}
static void
ts_object_set_property (GObject *gobject,
		guint prop_id,
		const GValue *value,
		GParamSpec *pspec)
{
	switch (prop_id) {
		case PROP_VERSION:
			g_free (TS_OBJECT(gobject)->version);
			TS_OBJECT(gobject)->version = g_value_dup_string (value);
			break;
		case PROP_DATA:
			g_clear_object (&(TS_OBJECT(gobject)->data));
			TS_OBJECT(gobject)->data = g_value_dup_object (value);
			break;
		default:
			break;
	}
}
static void
ts_object_get_property (GObject *gobject,
		guint prop_id,
		GValue *value,
		GParamSpec *pspec)
{
	switch (prop_id) {
		case PROP_VERSION:
			g_value_set_string(value, TS_OBJECT(gobject)->version);
			break;
		case PROP_DATA:
			g_value_set_object (value, TS_OBJECT(gobject)->data);
	//		g_value_set_boxed (value, &(TS_OBJECT(gobject)->data));
			break;
		default:
			break;
	}
}
static void
ts_object_class_init (TSObjectClass *klass)
{
	GObjectClass *gobject_class = G_OBJECT_CLASS(klass);

	gobject_class->set_property = ts_object_set_property;
	gobject_class->get_property = ts_object_get_property;
	//gobject_class->finalize = ts_object_finalize;

	g_object_class_install_property(gobject_class, PROP_VERSION,
			g_param_spec_string ("version", "Version", "Version",
				NULL, G_PARAM_READWRITE));
	g_object_class_install_property(gobject_class, PROP_DATA,
			g_param_spec_object ("data", "Data", "Data",
				TS_TYPE_DATA, G_PARAM_READWRITE));
}
static int port = 8080;
static char *root = NULL;
static GOptionEntry cmd_entries[] = {
  {"port", 'p', 0, G_OPTION_ARG_INT, &port,
   "Local port to bind to", NULL},
  {NULL}
};
static void
send_error (GOutputStream *out,
	    int error_code,
	    const char *reason)
{
  char *res;

  res = g_strdup_printf ("HTTP/1.0 %d %s\r\n\r\n"
			 "<html><head><title>%d %s</title></head>"
			 "<body>%s</body></html>",
			 error_code, reason,
			 error_code, reason,
			 reason);
  g_output_stream_write_all (out, res, strlen (res), NULL, NULL, NULL);
  g_free (res);
}

static gboolean
handler (GThreadedSocketService *service,
	 GSocketConnection      *connection,
	 GSocketListener        *listener,
	 gpointer                user_data)
{
  GOutputStream *out;
  GInputStream *in;
  GFileInputStream *file_in;
  GDataInputStream *data;
  char *line, *escaped, *tmp, *query, *unescaped, *path, *version;
  GFile *f;
  GError *error;
  GFileInfo *info;
  GString *s;
  void *mqtt = NULL;

  in = g_io_stream_get_input_stream (G_IO_STREAM (connection));
  out = g_io_stream_get_output_stream (G_IO_STREAM (connection));

  data = g_data_input_stream_new (in);
  /* Be tolerant of input */
  g_data_input_stream_set_newline_type (data, G_DATA_STREAM_NEWLINE_TYPE_ANY);
  line = g_data_input_stream_read_line (data, NULL, NULL, NULL);
  g_debug("%s[%d]line:%s\n", __FILE__, __LINE__, line);

  if (line == NULL)
    {
      send_error (out, 400, "Invalid request");
      goto out;
    }

  if (!g_str_has_prefix (line, "POST "))
    {
      send_error (out, 501, "Only POST implemented");
      goto out;
    }

  escaped = line + 5; /* Skip "POST " */

  version = NULL;
  tmp = strchr (escaped, ' ');
  if (tmp == NULL)
    {
      send_error (out, 400, "Bad Request");
      goto out;
    }
  *tmp = 0;

  version = tmp + 1;
  if (!g_str_has_prefix (version, "HTTP/1."))
    {
      send_error(out, 505, "HTTP Version Not Supported");
      goto out;
    }

  query = strchr (escaped, '?');
  if (query != NULL)
    *query++ = 0;

  unescaped = g_uri_unescape_string (escaped, NULL);
  g_debug("%s[%d]unescaped:%s\n", __FILE__, __LINE__, unescaped);
  if (!g_strcmp0(unescaped, "/setting/history_tree"))
   {
	   do {
		  line = g_data_input_stream_read_line (data, NULL, NULL, NULL);
		  g_debug("%s[%d]len:%d,line:%s\n", __FILE__, __LINE__, strlen(line), line);
	   } while (strlen(line) != 0);
	  line = g_data_input_stream_read_line (data, NULL, NULL, NULL);
	  g_debug("%s[%d]content:%s\n", __FILE__, __LINE__, line);
	  /*
	   const char *topic = NULL, *msg = NULL;
	   snprintf(topic, sizeof(topic)
	mqtt_send(mqtt, topic_add, obj_str, NULL);
	*/
   } else if (!g_strcmp0(unescaped, "/setting/hisry_tree")) {
   } else {
      send_error (out, 404, error->message);
   }

  s = g_string_new ("HTTP/1.0 200 OK\r\n");
  g_string_append_printf (s, "Content-Length: %"G_GINT64_FORMAT"\r\n",
			2);
  g_string_append (s, "Access-Control-Allow-Origin: *\r\n");
  g_string_append (s, "\r\n");

  if (g_output_stream_write_all (out,
				 s->str, s->len,
				 NULL, NULL, NULL))
    {
      g_output_stream_write_all (out,
				 "{}", 2,
				 NULL, NULL, NULL);
    }
  g_string_free (s, TRUE);

 out:
  g_object_unref (data);

  return TRUE;
}
GType test_object_get_type (void);
int main (int argc, char *argv[])
{
  GSocketService *service;
  GOptionContext *context;
  GError *error = NULL;
  void *mqtt = NULL;

  g_setenv ("G_MESSAGES_DEBUG", "all", TRUE);

  GFile *f;
  GFileInputStream *file_in;
  gboolean res;
  gsize n_bytes, len;
  gchar *contents;

  res = g_file_get_contents(
	  "docs/reference/post_mqtt/request.json", &contents, &len, &error);
  g_debug("read[len:%d]:%s\n", len, contents);
  GObject *obj;
  obj = json_gobject_from_data(TS_TYPE_OBJECT, contents, -1, &error);
  if (error) {
	  g_error("%s\n", error->message);
  }
  g_debug("version:%s\n", TS_OBJECT (obj)->version);
  TSData *data;
  data = TS_DATA(TS_OBJECT (obj)->data);
  g_debug("ip:%s\n", data->ip);
  /*
  gchar *value;
  g_object_get(obj, "version", &value);
  g_debug("value:%s\n", value);
  */
  g_free(contents);
  exit(1);
/*
  GDateTime *dt;
  dt = g_date_time_new_now_local();
  gchar *p = g_date_time_format_iso8601(dt);
  g_debug("time:%s\n", p);
  exit(1);
  */
	mqtt_init();
	mqtt = mosquitto_new("gwid", true, NULL);
	mqtt_connect_blocking(mqtt, "0.0.0.0", 1883);
  context = g_option_context_new ("<http root dir> - Simple HTTP server");
  g_option_context_add_main_entries (context, cmd_entries, NULL);
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  if (argc != 2)
    {
      g_printerr ("Root directory not specified\n");
      return 1;
    }

  root = g_strdup (argv[1]);

  service = g_threaded_socket_service_new (10);
  if (!g_socket_listener_add_inet_port (G_SOCKET_LISTENER (service),
					port,
					NULL,
					&error))
    {
      g_printerr ("%s: %s\n", argv[0], error->message);
      return 1;
    }

  g_print ("Http server listening on port %d\n", port);

  g_signal_connect (service, "run", G_CALLBACK (handler), mqtt);

  g_main_loop_run (g_main_loop_new (NULL, FALSE));
  g_assert_not_reached ();
}
